import { defineStore } from 'pinia'
import { ref, watch, computed } from 'vue'
import { SSEService } from '@/api/sseService'
import { v4 as uuidv4 } from 'uuid'
import { ElMessage } from 'element-plus'

interface SSEMessage {
  type: string
  message: string
}

export const useSseStore = defineStore(
  'sse',
  () => {
    const sseService = ref<SSEService | null>(null)
    const clientId = ref('')
    const messages = ref<SSEMessage[]>([])
    const previousConnectionState = ref(false)

    // 使用计算属性来获取实际的连接状态
    const isConnected = computed(() => {
      return Boolean(sseService.value?.isConnected)
    })

    // 监听连接状态变化
    watch(
      isConnected,
      (newValue) => {
        const wasConnected = previousConnectionState.value
        previousConnectionState.value = newValue

        // 连接状态改变时提示用户
        if (newValue && !wasConnected) {
          ElMessage.success('实时消息已连接')
        } else if (!newValue && wasConnected) {
          ElMessage.warning('实时消息已断开')
        }
      },
      { immediate: true },
    )

    // 初始化客户端ID
    const initClientId = () => {
      if (!clientId.value) {
        clientId.value = `web_${uuidv4()}`
        console.log('Generated new client ID:', clientId.value)
      }
    }

    // 处理接收到的消息
    const handleMessage = (message: SSEMessage) => {
      messages.value.push(message)
      // 根据消息类型处理不同的业务逻辑
      switch (message.type) {
        case 'notification':
          ElMessage.info(String(message.message))
          break
        case 'error':
          ElMessage.error(String(message.message))
          break
        case 'warning':
          ElMessage.warning(String(message.message))
          break
        case 'success':
          ElMessage.success(String(message.message))
          break
        default:
          console.log('Received message:', message)
      }
    }

    // 初始化SSE连接
    const initSSE = () => {
      try {
        console.log('Initializing SSE service...')
        initClientId()

        // 安全断开现有连接
        safeDisconnect()

        // 创建新的连接
        console.log('Creating new SSE service with client ID:', clientId.value)
        const service = new SSEService(clientId.value)

        // 验证service实例
        if (typeof service.disconnect !== 'function') {
          throw new Error('Invalid SSEService instance created')
        }

        // 添加消息处理器
        service.addMessageHandler(handleMessage)

        sseService.value = service
        service.connect()
      } catch (error) {
        console.error('Error initializing SSE service:', error)
        ElMessage.error('初始化SSE服务失败')
        sseService.value = null
      }
    }

    // 安全地断开现有连接
    const safeDisconnect = () => {
      if (sseService.value && typeof sseService.value.disconnect === 'function') {
        try {
          console.log('Safely disconnecting existing service')
          sseService.value.removeMessageHandler(handleMessage) // 移除消息处理器
          sseService.value.disconnect()
        } catch (error) {
          console.error('Error during safe disconnect:', error)
        }
      } else if (sseService.value) {
        console.warn('SSE service exists but disconnect is not a function')
      }
      sseService.value = null
    }

    // 断开连接
    const disconnectSSE = () => {
      try {
        console.log('Disconnecting SSE service')
        safeDisconnect()
        previousConnectionState.value = false
        messages.value = [] // 清空消息列表
      } catch (error) {
        console.error('Error disconnecting SSE service:', error)
      }
    }

    return {
      sseService,
      isConnected,
      clientId,
      messages,
      initSSE,
      disconnectSSE,
    }
  },
  {
    persist: {
      paths: ['clientId'],
      // 确保不会序列化 SSEService 实例
      serializer: {
        serialize: (state) => {
          const { clientId } = state
          return JSON.stringify({ clientId })
        },
        deserialize: (state) => {
          const parsed = JSON.parse(state)
          return {
            clientId: parsed.clientId,
            sseService: null,
            messages: [],
          }
        },
      },
    },
  },
)
